$(function () {
    function reset_token() {
        // 获取token
        $.post("/api/auth/login", {'username': "zmd_gps_admin", 'password': 'p@ssw0rd'}, function (res) {
           $("#tyibs_api_token").val(res.data.token);
        });
    }
    reset_token();

    var gps_address = $("#tyibs_lift_gps_address").val();
    var car_device_code = $("#tyibs_save_device_code").val();
    var lift_icon = new BMap.Icon("/er/static/src/img/warning.gif",new BMap.Size(80,80));
    var move_car_icon = new BMap.Icon("/lift_base/static/src/img/move_car.png", new BMap.Size(25, 50),{imageSize:new BMap.Size(25,50)});
    var stop_car_icon = new BMap.Icon('/lift_base/static/src/img/stop_car.png', new BMap.Size(25, 50),{imageSize:new BMap.Size(25,50)});
    var save_company_icon = new BMap.Icon("/lift_base/static/src/img/salvager_unit.png", new BMap.Size(32, 32));
    var map = new BMap.Map("tyibs-save-map");
    map.enableScrollWheelZoom(true);
    var car_marker = undefined;
    var polyline = new BMap.Polyline([], {strokeColor:"red", strokeWeight:8, strokeOpacity:1});
    var lift_point = "";
    show_response_company();

    var show_car = function (convertor) {
        if ($("#tyibs_api_token").val() == "") {
            reset_token();
        }
        $.ajax({
            async: true,
            url: '/api/device/gps/list',
            type: 'POST',
            data: {
                device_code: car_device_code
            },
            headers: {
                'x-access-token': $("#tyibs_api_token").val()
            },
            success: function (gps_data) {
                if (gps_data.code == 0 && gps_data.data.length > 0) {
                    convertor.translate([new BMap.Point(gps_data.data[0].lng, gps_data.data[0].lat)], 1, 5, function (data) {
                        if (data.status === 0) {
                            compute_time_and_space.search(data.points[0], lift_point);
                            if (car_marker != undefined) {
                                // marker已存在，更改其position
                                car_marker.setPosition(data.points[0]);
                                var polyline_path = polyline.getPath();
                                polyline_path.push(data.points[0]);
                                polyline.setPath(polyline_path);
                                compute_time_and_space.search(data.points[0], lift_point);
                                $(".tyibs_car_state").html(gps_data.data[0].state);
                                $(".tyibs_car_address").html(gps_data.data[0].address);
                                $(".tyibs_car_speed").html(gps_data.data[0].speed);
//                                    map.panTo(car_marker.getPosition());
                            } else {
                                // marker不存在，创建marker
                                car_marker = new BMap.Marker(data.points[0]);
                                map.addOverlay(car_marker);
                                car_marker.addEventListener('click', function (e) {
                                    set_info_window(car_marker,gps_data.data[0].state, gps_data.data[0].address, gps_data.data[0].speed);
                                });
                                var p = [];
                                var length = 10 ? gps_data.data.length > 10 : gps_data.data.length;
                                for (var i = 0; i < length; i++){
                                    p.push(new BMap.Point(gps_data.data[i].lng, gps_data.data[i].lat));
                                }
                                convertor.translate(p, 1, 5, function (res_data) {
                                    res_data.points.reverse();
                                    polyline.setPath(res_data.points);
                                });

                                map.addOverlay(polyline);
                                map.panTo(car_marker.getPosition());

                            }
                            // 修改小车车的icon
                            if (gps_data.data[0].speed > 0){
                                //车子在动
                                car_marker.setIcon(move_car_icon);
                            }else {
                                //车子静止
                                car_marker.setIcon(stop_car_icon);
                            }
                            //改变小车车方向
                            car_marker.setRotation(gps_data.data[0].direction);
                        }
                    });
                }
            }
        })
    }

    var compute_time_and_space = new BMap.DrivingRoute(map, {
        renderOptions: {},
        onSearchComplete: function (results) {
            if (compute_time_and_space.getStatus() != BMAP_STATUS_SUCCESS) {
                return;
            }
            var plan = results.getPlan(0);
            //获取时间
            var need_time = plan.getDuration(true);
            //获取距离
            var need_space = plan.getDistance(true);
            $("#time_" + car_device_code).html(need_time);
            $("#space_" + car_device_code).html(need_space);
        }
    });

    var set_info_window = function (marker, state, current_address,speed) {
        $.get("/er/client/map/dispatch/car/" + car_device_code, function (res) {
            res = JSON.parse(res);
            var info_window_html = '<div class="tyibs-map-info-window">'
                + '<h4>' + res.enterprise_name + '</h4><span>车牌号码：' + res.code + '</span>'
                + '<br/><span>GPS编码：' + car_device_code + '</span>'
                + '<br/><span>车载电话：' + res.GPS_mobile + '</span>'
                + '<br/><span>车辆负责人：' + res.manager + '</span>'
                + '<br/><span>负责人电话：' + res.manager_mobile + '</span>'
                + '<br/>当前位置：<span class="tyibs_car_address">' + current_address + '</span>'
                + '<br/>车辆状态：<span class="tyibs_car_state">'+ state +'</span>'
                + '<br/>当前车速：<span clsss="tyibs_car_speed">' + speed + '</span>km/h'
                + '<br/><span>距离事故电梯：<span id="space_' + car_device_code + '">获取中...</span></span>'
                + '<br/><span>所需时间：<span id="time_' + car_device_code + '">获取中...</span></span></div>';
            var infoWindow = new BMap.InfoWindow(info_window_html);
            infoWindow.addEventListener('open', function () {
                map.panTo(marker.getPosition());
                compute_time_and_space.search(marker.getPosition(), lift_point);
            });
            marker.openInfoWindow(infoWindow);
        });
    };

    // 先将电梯的导航地址转换为坐标，设置一个marker
    if (gps_address == ""){
        set_marker($("#tyibs_lift_lng").val(), $("#tyibs_lift_lat").val());
    }else {
        $.ajax({
            url: "http://api.map.baidu.com/geocoder/v2/?address=" + gps_address + "&output=json&ak=XYeVsCzcw7Rz0cCt3ZnZtBD2ohUTlMXX&callback=showLocation",
            dataType: 'jsonp',
            data: '',
            jsonp: 'callback',
            success: function (gps_result) {
                set_marker(gps_result.result.location.lng, gps_result.result.location.lat);
            },
            error: function () {
                alert("无法获取到位置。")
            }
        });
    }

    function set_marker(lng, lat) {
        lift_point = new BMap.Point(lng, lat);
        map.centerAndZoom(lift_point, 12);
        lift_marker = new BMap.Marker(lift_point, {icon: lift_icon});
        map.addOverlay(lift_marker);
        lift_marker.addEventListener('click', function (e) {
            var info_window_html = '<div class="tyibs-map-info-window">'
                                    + '<h4>' + $("#tyibs_lift_code").val() + '</h4>'
                                    + '<span>设备注册代码：' + $("#tyibs_lift_register_code").val() + '</span>'
                                    + '<br/><span>设备类别：' + $("#tyibs_lift_big_category").val() + '</span>'
                                    +' <br/><span>使用单位：'+ $("#tyibs_lift_use_company").val() +'</span>'
                                    + '<br/><span>维保单位：'+ $("#tyibs_lift_main_company").val() +'</span>'
                                    + '<br/><span>维保公司站点：' + $("#tyibs_lift_maintenance_site").val() + '</span>'
                                    + '<br/><span>维保公司救援人员：' + $("#tyibs_lift_maintenance_salvager").val() + '</span>'
                                    + '<br/><span>维保公司救援人员电话：' + $("#tyibs_lift_maintenance_salvager_mobile").val() + '</span>'
                                    +'</div>';
            var info_window = new BMap.InfoWindow(info_window_html);
            map.openInfoWindow(info_window,lift_point);
        });

        var convertor = new BMap.Convertor();
        if (car_device_code != ""){
            show_car(convertor);
            setInterval(function(){show_car(convertor)}, 1000 * 5);
        }
    }

    function show_response_company () {
        //显示响应单位marker
        if ($("#tyibs_response_company_id").val()){
            $.get("/er/client/map/get/response/company/" + $("#tyibs_response_company_id").val(), function (res) {
                res = JSON.parse(res);
                var response_company_marker = new BMap.Marker(new BMap.Point(res.lng, res.lat), {icon: save_company_icon});
                var label = new BMap.Label("响应单位",{offset   : new BMap.Size(-10, -25)});
                label.setStyle({color : "red"});
                response_company_marker.setLabel(label);
                map.addOverlay(response_company_marker);
                response_company_marker.addEventListener('click', function (e) {
                    var info_window_html = '<div class="tyibs-map-info-window">'
                                + '<h4>' + res.name + '</h4>'
                                + '<span>地址：'+ res.address +'</span>'
                                + '<br/><span>联系人：'+ res.contact +'</span><br/><span>手机：' + res.mobile + '</span>'
                                + '<br/><span>固定电话：' + res.phone + '</span><br/></div>';
                    var info_window = new BMap.InfoWindow(info_window_html);
                    response_company_marker.openInfoWindow(info_window);
                })
            })
        }
    }
})